﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using LDSP.BRL;
using BYFW.DAL;
using System.Data;
using LDSP.Util;
using System.IO;
using System.Text;
using LDSP.Helper;

namespace LDSP.UI.EnterpriseAdmin
{
    public partial class MngEGTaskPlan : BRL.BaseEnterpriseGroupAdminPage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                this.CheckQS();
            }
            if (this.RB())
            {
                this.InitDataDynamicBefore();
                if (!IsPostBack)
                {
                    History = 0;
                    this.InitialControls();
                    this.InitData();
                    this.GetCondition();
                    this.BindGrid();
                }
                this.InitDataDynamicAfter();
            }
        }

        private void InitialControls()
        {
            this.grd_list.Columns[col_subdiary_name].Visible = IsEnterpriseGroupAdmin;
            this.grd_list.Columns[col_exe_person].Visible = !IsEnterpriseGroupAdmin;
            this.grd_list.Columns[col_codification_name].Visible = false;
        }

        protected Codification m_codification = null;

        private int col_chb = 0;
        private int col_idx = 1;
        private int col_subdiary_name = 2;
        private int col_codification_name = 3;
        private int col_responsibility = 4;
        private int col_taskplan_name = 5;
        private int col_exe_person = 6;
        private int col_expire_dt = 7;
        private int col_progress = 8;
        private int col_update_dt = 9;
        private int col_comment = 10;
        private int col_status = 11;
        private int col_type = 12;

        /// <summary>
        /// 法规标准的ID
        /// </summary>
        protected int LastID
        {
            get { return this.GetVSInt("LastID"); }
            set
            {
                this.SetVS("LastID", value);
                m_codification = null;
            }
        }
        protected int History
        {
            get { return this.GetVSInt("History"); }
            set
            {
                this.SetVS("History", value);
            }
        }
        protected Codification Codification
        {
            get
            {
                if (m_codification == null)
                {
                    m_codification = new BRL.Codification();
                    if (LastID != 0)
                    {
                        m_codification.GetProperties(LastID);
                    }
                }

                return m_codification;
            }
        }

        protected bool IsEnterpriseGroupAdmin
        {
            get
            {
                return this.LoginUser != null && this.LoginUser.Enterprise != null && this.LoginUser.Enterprise.IsEnterpriseGroup == true;
            }
        }

        /// <summary>
        /// 传入参数，设置过滤条件
        /// </summary>
        protected void SetSpecialPageInfo()
        {
            g_pageInfo.Direction = true;
            g_pageInfo.Sort = "name";
            g_pageInfo.PageSize = this.LoginUser.Enterprise.EnterpriseConfig.LineQuantity;
            g_pageInfo.PageIndex = this.grd_list.PageIndex;
        }
        protected void CheckQS()
        {
            LastID = this.GetInt(this.Request.QueryString["id"]);
            if (Codification.ID == 0)
            {
                LastID = 0;
            }
        }

        protected bool RB()
        {
            bool res = true;
            if (LastID == 0)
            {
                this.JSAlert("请选择法律法规或标准添加计划！");
                this.JSGoBack();
                res = false;
            }
            else if (!HaveCatalogPermission(Codification.CatalogID))
            {
                this.JSAlert("您没有被授权该栏目！");
                this.JSGoBack();
                res = false;
            }
            return res;
        }
        protected void InitData()
        {
            //不缓存则清空页面信息
            if (!needCachePageInfo)
            {
                g_pageInfo.ClearPageInfo();
            }
            this.SetSpecialPageInfo();
            this.JSShowModalDialog("fid=" + LastID, this.btn_add);

            //记录一次法规/标准的查看.
            if (Codification != null)
            {
                Codification.ViewTimes++;
                Codification.Update();
            }
        }
        protected void InitDataDynamicBefore()
        {
        }
        protected void InitDataDynamicAfter()
        {
            History = History - 1;
        }

        protected void GetCondition()
        {
            //将favoriteID作为查询集合
            IList<Enterprise> enterprises = this.LoginUser.Enterprise.GetSubsidiaryList();
            IEnumerable<R_EnterpriseCodification> enterpriseCods = new List<R_EnterpriseCodification>();

            foreach (Enterprise enterprise in enterprises)
            {
                enterpriseCods = enterpriseCods.Concat<R_EnterpriseCodification>(
                    new R_EnterpriseCodification().GetListByEnterpriseAndCodification(enterprise.ID, Codification.ID));
            }

            StringBuilder favorateIdBuilder = new StringBuilder();
            foreach (R_EnterpriseCodification r_ec in enterpriseCods)
            {
                favorateIdBuilder.Append(r_ec.ID.ToString() + ";");
            }

            string cond = string.Empty;
            if (!String.IsNullOrEmpty(favorateIdBuilder.ToString()))
            {
                cond = DefaultDB.GetSQLInAndNotInCondition("favoriteID", EDataType.Int, favorateIdBuilder.ToString(), true, false);
            }
            else
            {
                cond = DefaultDB.GetSQLInAndNotInCondition("favoriteID", EDataType.Int, "-1", true, false);
            }
            g_pageInfo.Condition = cond;
        }
        protected void BindGrid()
        {
            this.grd_list.PageSize = g_pageInfo.PageSize;
            this.grd_list.PageIndex = g_pageInfo.PageIndex;
            this.grd_list.DataSource = BYFW.SFL.CommonOP.SortedTable(new Plan().GetRecords(g_pageInfo.ConditionWhere, true), g_pageInfo.GetSortExpression());
            this.grd_list.DataBind();
        }

        protected void btn_add_Click(object sender, EventArgs e)
        {
            try
            {
                this.GetCondition();
                this.BindGrid();
            }
            catch (Exception ex)
            {
                this.HandlerException(ex);
            }
        }
        protected void btn_delete_Click(object sender, EventArgs e)
        {
            try
            {
                this.DeleteCheckedInGrid<Plan>(this.grd_list);
                this.BindGrid();
            }
            catch (Exception ex)
            {
                this.HandlerException(ex);
            }
        }
        protected void btn_export_Click(object sender, EventArgs e)
        {
            DataTable dt = BYFW.SFL.CommonOP.SortedTable(new Plan().GetRecords(g_pageInfo.ConditionWhere, true), g_pageInfo.GetSortExpression());

            //获取模板
            string file = Server.MapPath("..\\..\\..\\Templates\\UserSpecified\\Plan\\" + this.LoginUser.EnterpriseID + ".xls");
            string template = !string.IsNullOrEmpty(this.LoginUser.Enterprise.EnterpriseConfig.TaskPlanTemplateName) ? file : Server.MapPath("..\\..\\..\\Templates\\TaskPlan.xls");

            new TaskPlanExport().Export(this.Server, dt, template);
        }
        protected void btn_goback_Click(object sender, EventArgs e)
        {
            try
            {
                this.JSGoBackHistory();
            }
            catch (Exception ex)
            {
                this.HandlerException(ex);
            }
        }

        protected void grd_list_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            try
            {
                int id = this.GetInt(e.CommandArgument.ToString());
                if (e.CommandName == "deleteItem")
                {
                    Plan ett = new Plan();
                    ett.GetProperties(id);
                    ett.Delete();
                }
                this.BindGrid();
            }
            catch (Exception ex)
            {
                this.HandlerException(ex);
            }
        }
        protected void grd_list_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            try
            {
                if (e.Row.RowType == DataControlRowType.DataRow)
                {
                    Plan ett = new Plan();
                    ett.GetProperties(((DataRowView)e.Row.DataItem).Row);
                    this.ShowSequenceNumber(e.Row, 1);

                    //复选框
                    CheckBox chk = (CheckBox)e.Row.FindControl("chb");
                    chk.Enabled = ett.Type == 1;

                    //修改按钮
                    WebControl c = (WebControl)e.Row.FindControl("lnk_update");
                    this.JSShowModalDialog("pid=" + ett.ID, c);

                    //删除按钮
                    WebControl c1 = (WebControl)e.Row.FindControl("lnk_delete");
                    c1.Visible = ett.Type == 1;

                    e.Row.Cells[col_subdiary_name].Text = ett.EnterpriseCodification.Enterprise.Code;
                    e.Row.Cells[col_expire_dt].Text = this.FormatDT(ett.ExpiredDT);
                    e.Row.Cells[col_update_dt].Text = this.FormatDT(ett.ChangeDT);
                    e.Row.Cells[col_status].Text = ((TaskStatus)ett.Status).ToString();
                    e.Row.Cells[col_type].Text = ((TaskPlanType)ett.Type).ToString();
                    e.Row.Cells[col_progress].Text = ett.Progress.Replace("\n", "</br>");
                    e.Row.Cells[col_comment].Text = ett.Comment.Replace("\n", "</br>");

                    UIHelper.AppendEmptyLine(e.Row, col_taskplan_name, col_progress);

                    //责任人
                    string principleStr = GetPrincipleListStr(new R_PlanPrinciple().GetListByPlan(ett.ID));
                    if (!string.IsNullOrEmpty(principleStr))
                    {
                        e.Row.Cells[col_responsibility].Text = principleStr;
                    }

                    //粗体显示未查看任务
                    R_User_ViewPlan uvp = new R_User_ViewPlan().GetByUserAndPlan(this.LoginUser.ID, ett.ID);
                    if (uvp == null || uvp.ViewDT < ett.ChangeDT)
                    {
                        e.Row.Font.Bold = true;
                    }
                }
            }
            catch (Exception ex)
            {
                this.HandlerException(ex);
            }
        }
        protected void grd_list_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            try
            {
                g_pageInfo.PageIndex = e.NewPageIndex;
                this.BindGrid();
            }
            catch (Exception ex)
            {
                this.HandlerException(ex);
            }
        }
        protected void grd_list_Sorting(object sender, GridViewSortEventArgs e)
        {
            try
            {
                if (g_pageInfo.Sort == e.SortExpression)
                {
                    g_pageInfo.Direction = !g_pageInfo.Direction;
                }
                else
                {
                    g_pageInfo.Direction = true;
                }
                g_pageInfo.Sort = e.SortExpression;
                this.BindGrid();
            }
            catch (Exception ex)
            {
                this.HandlerException(ex);
            }
        }

        private void JSShowModalDialog(string arg, WebControl ctrl)
        {
            this.JSShowDialog("../EnterpriseAdmin/Operation/AddTaskPlan.aspx?" + arg, 1200, 500, ctrl, null, null, null, null, null, null, null, true, null, null, null, null, null);
        }
        private void JSGoBackHistory(bool first = true)
        {
            string script = string.Format("window.history.go({0});", History);
            if (first)
            {
                this.JSFirst(script);
            }
            else
            {
                this.JS(script);
            }
        }
    }
}